﻿using UnityEngine;
using System.Collections;

public class AttackObjScript : MonoBehaviour {
	public GameObject ref_damageNumber;
	public GameObject pool_damageNumber;
	public Sprite[] damageNumberSprites;
	public int damageDeal;

	BoxCollider2D attackObjCollider;
	bool damageNumberIsShown = false;

	// Use this for initialization
	void Start () {
		attackObjCollider = GetComponent<BoxCollider2D>();
	}
	
	// Update is called once per frame
	void FixedUpdate () {

		if(attackObjCollider.enabled){

			if(!damageNumberIsShown){
				//Display the Damage Number on top (Y+1) of this Attack Object
				displayDamageNumber( damageDeal.ToString(), new Vector2(transform.position.x, transform.position.y+1) );
				damageNumberIsShown = true;
			}

			Invoke("disableAttackObjCollider", 0.5f);	//run disableAttackObjCollider() after 0.5 second

		}

	} //FixedUpdate()

	//assuming damage will not be more than 999,999,999 (nine digits)
	void displayDamageNumber(string dmgString, Vector2 coord){
		
		float totalStringWidth = (dmgString.Length-1f)/2f;
		totalStringWidth *= 0.6f;
		Vector2 numberPosition = new Vector2( (coord.x-totalStringWidth), coord.y);
		int sprArrayIndex = 0;
		foreach(char singleDigitStr in dmgString.ToCharArray()){
			switch(singleDigitStr)
			{
			case '0':
				sprArrayIndex = 0;
				break;
			case '1':
				sprArrayIndex = 1;
				break;
			case '2':
				sprArrayIndex = 2;
				break;
			case '3':
				sprArrayIndex = 3;
				break;
			case '4':
				sprArrayIndex = 4;
				break;
			case '5':
				sprArrayIndex = 5;
				break;
			case '6':
				sprArrayIndex = 6;
				break;
			case '7':
				sprArrayIndex = 7;
				break;
			case '8':
				sprArrayIndex = 8;
				break;
			case '9':
				sprArrayIndex = 9;
				break;
			}
			
			GameObject newObj = (GameObject)Instantiate(ref_damageNumber);
			newObj.transform.parent = pool_damageNumber.transform;
			newObj.AddComponent<DamageNumberFloating>().displayNumber(numberPosition, damageNumberSprites[sprArrayIndex]);
			numberPosition.x += 0.6f;
		}//foreach

	}

	void disableAttackObjCollider(){
		attackObjCollider.enabled = false;
		damageNumberIsShown = false;
	}

}
